package aorise.com.frame.ui.login;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import aorise.com.frame.FsApplication;
import aorise.com.frame.MainActivity;
import aorise.com.frame.R;
import aorise.com.frame.base.ActivityManager;
import aorise.com.frame.base.BBBaseActivity;
import aorise.com.frame.bean.SysUserModel;
import aorise.com.frame.common.BAST64Utils;
import aorise.com.frame.network.ApiService;
import aorise.com.frame.network.BuildConfig;
import aorise.com.frame.network.CustomSubscriber;
import aorise.com.frame.network.Result;
import aorise.com.frame.view.LineEditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginActivity extends BBBaseActivity {


//    @BindView(R.id.loading)
//    ImageView loading;
//    @BindView(R.id.edt_username)
//    EditText edtUsername;
//    @BindView(R.id.edt_pwd)
//    EditText edtPwd;
    @BindView(R.id.edt_username)
    LineEditText edtUsername;
    @BindView(R.id.edt_pwd)
    LineEditText edtPwd;
    @BindView(R.id.cb_remember)
    CheckBox cbRemember;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.txt_hint)
    TextView txtHint;
    private SharedPreferences sr;
    private  boolean isLogin  = false;
    @Override
    protected void initView() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //将存储的用户名密码设置到EditText,如果没有则为"".
        ((FsApplication) getApplication()).setToken("");//初始化token
        sr = getSharedPreferences("RememberAccount", Context.MODE_PRIVATE);
        String username = sr.getString("username", "");
        String password = sr.getString("password", "");
        boolean flag = sr.getBoolean("flag", false);//是否勾选记住密码
        if (flag) {
            cbRemember.setChecked(true);
        } else {
            cbRemember.setChecked(false);
        }
        edtUsername.setText(username);
        SharedPreferences sp = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.apply();
        if (username.length() > 0) {
            edtUsername.setSelection(username.length());//光标移动到最后
        }
        if (password!=null){
            password = BAST64Utils.decode(password);
        }
        edtPwd.setText(password);
        //禁止输入空格
        edtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(" ")) {
                    String trim = charSequence.toString().trim();
                    edtUsername.setText(trim);
                    edtUsername.setSelection(i);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                edtPwd.setText("");
            }
        });
        //禁止输入空格
        edtPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(" ")) {
                    String trim = charSequence.toString().trim();
                    edtPwd.setText(trim);
                    edtPwd.setSelection(i);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {

    }

    /**
     * 登录
     *
     * @param username
     * @param password
     */
    private void login(final String username, final String password) {
        ApiService.Utils.getApiService(this).login(username, password)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomSubscriber<Result<SysUserModel>>(this,true) {
                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        // loading.clearAnimation();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        //  loading.clearAnimation();
//                        showToast("网络错误！");
                    }

                    @Override
                    public void onNext(Result<SysUserModel> userInfoResult) {
                        super.onNext(userInfoResult);
                        SharedPreferences.Editor editor = sr.edit();//记住密码sp
                        SharedPreferences sp = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);//用户信息sp
                        SharedPreferences.Editor edit = sp.edit();
                        //登录信息返回成功
                        if (userInfoResult.getCode() == BuildConfig.SUCCESS_CODE) {
                            edit.putString("password", password);//用于修改密码（原始密码是否正确）
                            SysUserModel data = userInfoResult.getData();
                            edit.putInt("userid", data.getUserId());//用于修改密码（userid参数）
                            edit.apply();
                            //是否记住账号密码
                            if (cbRemember.isChecked()) {
                                //记住账号密码
                                editor.putString("username", username);
                                editor.putString("password", password);
                                editor.putBoolean("flag", true);//保存勾选记住密码状态
                            } else {
                                //清空账户与密码
                                editor.clear();
                            }
                            editor.apply();//保存记住密码sp
                            ((FsApplication) getApplication()).setToken(data.getToken());//用于修改密码（token）以及登录正确请求header token
                            txtHint.setVisibility(View.INVISIBLE);//用户名密码正确（账号密码错误提示）影藏
//                            if (!edtPwd.getText().toString().equals(BuildConfig.DEFAULT_PWD)) {
                            //存储登录信息的
                            edit.putString("username", data.getAccount());
                            edit.putString("name", data.getUserName());
                            edit.putString("suborrole", data.getSuborRole());
                            edit.putInt("type", data.getType());
                            edit.putInt("relateid", data.getOrganId());
                            System.out.println("relateid" + data.getOrganId());
                                for (SysUserModel.MapListBean mapListBean : data.getMapList()) {
                                    if (mapListBean.getPermissId()==40){
                                        isLogin = true;
                                        for (SysUserModel.MapListBean.SysPermissionModelsBeanX sysPermissionModel : mapListBean.getSysPermissionModels()) {
                                            if (sysPermissionModel.getPermissId() == 401) {
                                                edit.putBoolean("news_query", true);//新闻公告
                                            } else if (sysPermissionModel.getPermissId() == 402) {
                                                edit.putBoolean("company_query", true); //企业查询
                                            } else if (sysPermissionModel.getPermissId() == 403) {
                                                edit.putBoolean("jobholder_query", true); //从业人员查询
                                            } else if (sysPermissionModel.getPermissId() == 404) {
                                                edit.putBoolean("laws_query", true);//法律法规查询
                                            } else if (sysPermissionModel.getPermissId() == 405) {
                                                edit.putBoolean("contacts_query", true);//通讯录查询
                                            } else if (sysPermissionModel.getPermissId() == 406) {
                                                edit.putBoolean("auto_warning", true);//自动预警查询
                                            } else if (sysPermissionModel.getPermissId() == 407) {
                                                edit.putBoolean("daylycheck_query", true);//日常检查查询
                                            } else if (sysPermissionModel.getPermissId() == 408) {
                                                edit.putBoolean("enforce_query", true);//行政执法查询
                                            }else if (sysPermissionModel.getPermissId() == 409) {//
                                                edit.putBoolean("statistical_query", true);//统计分析查询
                                            }else if (sysPermissionModel.getPermissId() == 410) {//
                                                edit.putBoolean("production_query", true);//食品生产查询
                                            }else if (sysPermissionModel.getPermissId() == 411) {//
                                                edit.putBoolean("trade_query", true);//食品交易查询
                                            }
                                            for (SysUserModel.MapListBean.SysPermissionModelsBeanX.SysPermissionModelsBean permissionModel : sysPermissionModel.getSysPermissionModels()) {
                                                if (permissionModel.getParentId() == 407) {
                                                    if (permissionModel.getPermissId() == 4071) {
                                                        edit.putBoolean("daylycheck_deal", true);//日常检查处理
                                                    }
                                                } else if (permissionModel.getParentId() == 408) {

                                                    if (permissionModel.getPermissId() == 4081) {
                                                        edit.putBoolean("enforce_deal", true);//行政执法处理
                                                    }
                                                }
                                            }
                                        }
                                    }

                            }
                            edit.apply();//保存用户信息sp
                            if (isLogin){
                                isLogin = false;
                                openActivity(MainActivity.class);//跳转到首页
                            }else {
                                showToast("当前账号无权限登录，等联系管理员");
                            }

                        }
//                            else {//如果是默认密码
//                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
//                                builder.setTitle("提示！")
//                                        .setNegativeButton("取消", null)
//                                        .setPositiveButton("去修改", new DialogInterface.OnClickListener() {
//                                            @Override
//                                            public void onClick(DialogInterface dialogInterface, int i) {
//                                                startActivity(new Intent(LoginActivity.this, ChangePwdActivity.class));
//                                            }
//                                        }).setMessage("请修改默认密码，否则无法登录！").show();
//                            }
//                        }
                        else {
                            //登录失败
                            if (userInfoResult.getMessage().equals("9999")) {
                                txtHint.setText("服务器出错！");
                            } else {
                                txtHint.setText(userInfoResult.getMessage());
                            }
                            txtHint.setVisibility(View.VISIBLE);//用户名密码错误（账号密码错误提示）可见
                            edtPwd.setText("");
                            editor.clear().apply();
                        }
                    }
                });
    }

    @OnClick({R.id.cb_remember, R.id.bt_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                  openActivity(MainActivity.class);
//                String username = edtUsername.getText().toString();
//                String edtpwd = edtPwd.getText().toString();
////                //用户名6-20字符 密码6-20字符
//                if (username.length() > 5 && username.length() < 21) {
//                    if (edtpwd.length() > 5 && edtpwd.length() < 21) {
//                        //Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotateanim);
//                        //loading.startAnimation(animation);
//                        login(username, BAST64Utils.encode(edtpwd));//登录
//                    } else {
//                        showToast("请输入6到20个字符密码！");
//                    }
//                } else {
//                    showToast("请输入6到20个字符用户名！");
//                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
        ActivityManager.getInstance().appExit(getApplicationContext());
    }
}
